package com.chen.cloudpicture.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.chen.cloudpicture.config.CosClientConfig;
import com.chen.cloudpicture.exception.BusinessException;
import com.chen.cloudpicture.exception.ErrorCode;
import com.chen.cloudpicture.manager.CosManager;
import com.chen.cloudpicture.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * FileManager有本地文件上传和URL上传图片两种方式，但二者流程极为相似，仅少数几个细节流程不同。
 * 所以可以使用设计模式：模板模式。设计模式就是在代码比较复杂，同时会有很多重复代码的场景下使用的。
 * 模板模式：定义一个抽象类，里面放入所有通用的流程，具体细节不同用抽象方法表示，通过子类继承模板并实现不同的细节方法
 * <p>
 * 两种方法的实现流程都是1.校验文件 2.获取上传地址 3.获取本地临时文件 4.上传到对象存储 5.封装解析得到的图片信息 6.清理临时文件。
 * 只有三个不同实现细节：1.校验图片 2.获取文件名称 3.将文件信息保存到临时文件。
 */
@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;

    /**
     * 上传图片(压缩优化后的)
     * <p>
     * inputSource这里只有两种变量类型，所以使用Object，再多一些可以使用泛型
     *
     * @param inputSource      文件来源
     * @param uploadPathPrefix 上传的路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1.校验图片 ***第一个抽象方法
        validPicture(inputSource);
        // 2.生成图片上传地址
        String uuid = RandomUtil.randomString(16);
        // 获取原文件名 ***第二个抽象方法
        String originalFilename = getOriginalFilename(inputSource);
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        // 拼接文件上传地址，当前日期加随机数加原文件后缀,format格式化,%s占位符
        // 因为原文件名可能重复，有些特殊文件名可能还由特殊字符影响上传
        String uploadFileName = String.format("%s_%s.%s", uploadPathPrefix, uuid, fileSuffix);
        // 最终上传地址
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            // 3.创建临时文件，获取文件到服务器，第一个参数是文件前缀，第二个参数是文件后缀，默认是.tmp
            file = File.createTempFile(uploadFilePath, null);
            // 处理文件来源 ***第三个抽象方法
            processFile(inputSource, file);
            // 4.上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            // 5.获取图片信息对象，封装返回结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 图片压缩后要根据写入的规则重新获取解析结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                // 获取压缩之后得到的文件元信息
                CIObject compressedCiObject = objectList.get(0);
                // 缩略规则（默认等于压缩图）
                CIObject thumbnailCiObject = compressedCiObject;
                if(objectList.size() > 1){
                    thumbnailCiObject = objectList.get(1); // 有生成缩略图，才获取缩略图
                }
                // 封装处理图片规则后的返回结果
                return buildResult(originalFilename, compressedCiObject, thumbnailCiObject, imageInfo);
            }
            return buildResult(imageInfo, originalFilename, file, uploadFilePath);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 6.清理临时文件
            deleteTempFile(file);
        }
    }


    protected abstract void processFile(Object inputSource, File file) throws IOException;

    protected abstract String getOriginalFilename(Object inputSource);

    protected abstract void validPicture(Object inputSource);


    /**
     * 封装处理图片规则后的返回结果
     * @param originalFilename 原始文件名
     * @param compressedCiObject 压缩后的对象,封装了各种文件元信息
     * @param thumbnailCiObject 缩略图后的对象,封装了各种文件元信息
     * @param imageInfo 图片信息
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailCiObject,
                                            ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setUrl(cosClientConfig.getHost() +"/"+ compressedCiObject.getKey()); // 压缩图片地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey()); // 缩略图片地址
        uploadPictureResult.setPicColor(imageInfo.getAve()); // 图片主色调，数据万象直接获得
        return uploadPictureResult;
    }

    // 封装返回结果
    private UploadPictureResult buildResult(ImageInfo imageInfo, String originalFilename, File file, String uploadFilePath) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilePath);
        uploadPictureResult.setPicColor(imageInfo.getAve()); // 图片主色调，数据万象直接获得
        return uploadPictureResult;
    }

    /**
     * // 清理临时文件
     */
    private static void deleteTempFile(File file) {
        if (file != null) {
            boolean delete = file.delete();
            if (!delete) {
                log.warn("file delete err, filepath = {}", file.getAbsoluteFile());
            }
        }
    }


}
